import { extend, isObject } from "../shared";
import { track, trigger } from "./effect";
import { reactive, ReactiveFlages, readonly } from "./reactive";

const get = createGetter()
const set = createSetter()
const readonlyGet = createGetter(true)
const shallowReadonlyGet = createGetter(true, true)

function createGetter(isReadonly = false, shallow = false) {
    return function get(target, key) {

        // 实现 isReactive
        if (key === ReactiveFlages.IS_REACTIVE) {
            return !isReadonly
        }

        // 实现 isReadonly
        if (key === ReactiveFlages.IS_READONLY) {
            return isReadonly
        }

        const res = Reflect.get(target, key);

        if (shallow) {
            return res
        }

        // 看看 res 是不是 object
        if (isObject(res)) {
            return isReadonly ? readonly(res) : reactive(res)
        }
    
        if (!isReadonly) {
            track(target, key)
        }
        return res;
    }
}

function createSetter() {
    return function set(target, key, value) {
        const res = Reflect.set(target, key, value);

        trigger(target, key)
        return res;
    }
}

export const mutableHandlers = { get, set }

export const readonlyHandlers = {
    get: readonlyGet,
    set(target, key, value) {
        console.warn(`key:${key} 不可被set，因为target是readonly`, target)
        return true
    }
}

export const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
    get: shallowReadonlyGet
})